﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WhiteFox.DAlessio.Agenda.View.Controllers;
using WhiteFox.DAlessio.Patterns.UI.MVC;

namespace WhiteFox.DAlessio.Agenda.View
{    
    public partial class frmMain : frmMainView, IView
    {
        BackgroundWorker bw = new BackgroundWorker();

        public frmMain()
        {
            InitializeComponent();

            this.dgv.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgv_CellClick);
            this.Load += frmMain_Load;

            bw.DoWork += bw_DoWork;
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Invoke((MethodInvoker)delegate
            {
                LoadData();
            });
        }

        void frmMain_Load(object sender, EventArgs e)
        {
            InitData(true);
            Controller.RegisterView(this);
        }

        public void ModelChange(object sender, ModelChangeEventArgs e)
        {
            InitData(e.ForceChange);
        }

        public void InitData(bool isForceLoad)
        {
            if (isForceLoad)
                bw.RunWorkerAsync();
        }

        private void LoadData()
        {
            dgv.DataSource = Controller.Domain.Repository.GetAll();
            dgv.Columns["Telefones"].Visible = false;
        }

        private void btnNovo_Click(object sender, EventArgs e)
        {
            using (frmCadastrar view = new frmCadastrar())
            {
                view.ShowDialog();
            }

        }

        private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                var id = dgv.Rows[e.RowIndex].Cells[0];

                if (id != null)
                {
                    var contato = Controller.Domain.Repository.GetByID(int.Parse(id.Value.ToString()));
                    using (frmCadastrar view = new frmCadastrar(contato))
                    {
                        view.ShowDialog();
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WhiteFox.DAlessio.Agenda.Services.Exportar.GerarXML();
        }
    }

    //Classe necessária para que o Form seja visualizado em modo Designer (o modo Designer não consegue renderizar o Form em classes com herança genérica)
    public class frmMainView : ViewBase<ContatoControler> { }   
}
